package org.dxy.domain.handler.productionLine;

import com.google.common.eventbus.EventBus;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dxy.domain.handler.CommandHandler;
import org.dxy.domain.port.repository.IProductionLineRepository;
import org.dxy.domain.command.productionLine.ReportProductionLineAlarmCommand;
import org.dxy.domain.model.aggregate.ProductionLine;
import org.dxy.types.common.CommandResult;
import org.springframework.stereotype.Component;

/**
 * @description: 报告产线报警命令处理器
 * @author: dxy
 * @createTime: 2025/6/26 10:30
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class ReportProductionLineAlarmCommandHandler implements CommandHandler<ReportProductionLineAlarmCommand, Void> {

    private final IProductionLineRepository productionLineRepository;
    private final EventBus eventBus;

    @Override
    public CommandResult<Void> handle(ReportProductionLineAlarmCommand command) {
        ProductionLine productionLine = productionLineRepository.findById(command.getLineId());
        if (productionLine == null) {
            log.error("未找到产线，command={}", command);
            return CommandResult.fail("产线不存在");
        }

        try {
            productionLine.reportAlarm(command);
            productionLineRepository.save(productionLine);
            productionLine.getDomainEvents().forEach(eventBus::post);
            productionLine.clearDomainEvents();
            
            log.info("报告产线报警成功, command={}", command);
            return CommandResult.success("报告产线报警成功");
        } catch (IllegalStateException e) {
            log.warn("报告产线报警失败，原因：{}", e.getMessage());
            return CommandResult.fail(e.getMessage());
        }
    }
} 